<template>
  <div class="user-chat">
    <van-nav-bar
      class="app-nav-bar"
      title="小智同学"
      left-arrow
      @click-left="$router.back()"
    />
    <van-cell-group class="chat-wrap" ref="chat-list">
      <van-cell
        v-for="(item, index) in messages"
        :key="index"
        :title="item.msg"
      >
      </van-cell>
    </van-cell-group>
    <van-cell-group class="send-message-wrap">
      <van-field
        v-model="message"
        placeholder="请输入消息"
        :border="false"
      />
      <van-button class="send-message-btn" type="primary" size="small" @click="onSend">发送</van-button>
    </van-cell-group>
  </div>
</template>

<script>
import { io } from 'socket.io-client'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'UserChat',
  props: {},
  components: {},
  data () {
    return {
      message: '',
      socket: null,
      messages: getItem('CHAT_MESSAGE') || []
    }
  },
  computed: {},
  watch: {
    messages () {
      setItem('CHAT_MESSAGE', this.messages)
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    }
  },
  methods: {
    onSend () {
      const data = {
        msg: this.message,
        timestamp: Date.now()
      }
      this.socket.emit('message', data)
      this.messages.push(data)
      this.message = ''
    },
    scrollToBottom () {
      const list = this.$refs['chat-list']
      list.scrollTop = list.scrollHeight
    }
  },
  created () {
    const socket = io('http://ttapi.research.itcast.cn')
    this.socket = socket
    socket.on('connect', () => {
      console.log('connent')
    })
    socket.on('disconnect', () => {
      console.log('disconnect')
    })
    socket.on('message', (data) => {
      this.messages.push(data)
    })
  },
  mounted () {
    this.scrollToBottom()
  },
  destroyed () {
  }
}
</script>

<style scoped lang='less'>
.chat-wrap {
  position: fixed;
  left: 0;
  right: 0;
  top: 46px;
  bottom: 44px;
  overflow-y: auto;
}
.send-message-wrap {
  display: flex;
  padding: 0 14px;
  align-items: center;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
}
.send-message-btn {
  width: 50px;
}
</style>
